Examples of plotly

We are going to look at instacart dataset.

library(tidyverse)
## ── Attaching packages ───────────────────────────────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.2     ✓ purrr   0.3.4
## ✓ tibble  3.0.3     ✓ dplyr   1.0.2
## ✓ tidyr   1.1.2     ✓ stringr 1.4.0
## ✓ readr   1.3.1     ✓ forcats 0.5.0
## ── Conflicts ──────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(p8105.datasets)
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
data("instacart")

Plotly plots

boxplot

Among all department, when do customers usually place an order within a day?

y <- list(
  title = "Hour of a day"
)

instacart %>% 
  plot_ly(x = ~department, y = ~order_hour_of_day, type = "box") %>% 
  layout(yaxis = y)
## Warning: `arrange_()` is deprecated as of dplyr 0.7.0.
## Please use `arrange()` instead.
## See vignette('programming') for more help
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_warnings()` to see where this warning was generated.

bar graph

Among all departments, which department is the most popular for users?

y <- list(
  title = "number of order"
)

instacart %>% 
  count(department) %>% 
  mutate(
    department = fct_reorder(department,n)) %>% 
  plot_ly(
    x = ~department, y = ~n, color = ~department, 
    type = "bar", colors = "viridis") %>% 
  layout(yaxis = y)

violin plot

Is the size of the order related to days since prior order?

x <- list(
  title = "Days since prior order"
)

y <- list(
  title = "Items in an order"
)


instacart %>% 
  group_by(order_id) %>% 
  mutate(
    num_per_order = n(),
    text_label=str_c("Days:", days_since_prior_order, "\nItems in an order:", num_per_order)) %>% 
  distinct(order_id, num_per_order, days_since_prior_order, text_label) %>% 
  plot_ly(
    x = ~days_since_prior_order, y = ~num_per_order, text = ~text_label,
    type = "violin", colors = "viridis") %>% 
   layout(xaxis = x, yaxis = y)